package com.solution.admin.settings.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.solution.admin.settings.entity.DictEntity;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.DictService;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.constants.PublicStatus.IS_DELETE;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.BaseReturn;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.StringUtils;

/**
 * 字典查询controller 组件 (需要重新改写)
 * @author james
 */
@RequestMapping("/dict")
@Controller
public class KeyMapController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(KeyMapController.class);

	@Autowired
	private KeyMapService keyMapService;

	@Autowired
	DictService dictService;
	
	
	/**
	 * 查询获取所有数据字典信息
	 * 
	 * @param request
	 * @return
	 * @author zhaieryuan
	 * @date 2017年4月19日 下午3:03:12
	 */
	@RequestMapping("/list")
	@ResponseBody
	public List<KeyMapEntity> listDict(HttpServletRequest request, @RequestParam(required = true) String keyType) {
		List<KeyMapEntity> dictList = keyMapService.listKeyMap(keyType);
		if(dictList == null){
			dictList = new ArrayList<KeyMapEntity>();
		}
		return dictList;
	}

	/**
	 * @param CategoryEntity
	 * @param request
	 * @param response
	 * @return
	 * @descrption 分类列表
	 * @exception/throws [异常类型][异常说明]
	 * @author 翟二远
	 * @date 2017年4月12日 下午4:01:35
	 */
	@RequestMapping("/toKeyMapListPage")
	public String toBrandListPage(HttpServletRequest request, HttpServletResponse response, Model model) {

		return "/settings/keymap_list";
	}

	/**
	 * 新增下拉属性
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @author zhaieryuan
	 * @date 2017年5月8日 下午2:45:12
	 */
	@RequestMapping("/toKeyMapAddPage")
	public ModelAndView toKeyMapAddPage(HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute("opFlag", "add");
		ModelAndView mv = new ModelAndView("/settings/keymap_manage/keymap_form");
		return mv;
	}

	/**
	 * 字典列表
	 * 
	 * @Title: listDict
	 * @Description:(描述)
	 * @param request
	 * @return JSONGrid
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年8月26日 下午4:47:01
	 */
	@RequestMapping("/listDict")
	@ResponseBody
	public JSONGrid listDict(HttpServletRequest request) {
		// 返回结果集查询
		JSONGrid resultList = new JSONGrid();
		try {
			List<DictEntity> list = dictService.listDict(null);
			resultList.setRows((null != list && list.size() > 0) ? list : null);
			resultList.setTotal((null != list && list.size() > 0) ? list.size() : 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

	/**
	 * 根据类型或者名称查询字典<br>
	 * 1=已存在<br>
	 * 0=尚未存在
	 * 
	 * @Title: getDict
	 * @Description:(描述)
	 * @param request
	 * @param dictType
	 * @param dictName
	 * @return String
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年8月26日 下午4:52:03
	 */
	@RequestMapping("/getDict")
	@ResponseBody
	public String getDict(HttpServletRequest request, String dictType, String dictName) {
		String code = "1";
		try {
			// 有一个不为空
			if (StringUtils.isNotEmpty(dictType) || StringUtils.isNotEmpty(dictName)) {
				DictEntity dict = dictService.getDict(dictType, dictName);
				code = (null == dict) ? "0" : "1";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return code;
	}

	/**
	 * 保存字典
	 * 
	 * @Title: saveDict
	 * @Description:(描述)
	 * @param request
	 * @param dictType
	 * @param dictName
	 * @return String
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年8月26日 下午4:53:52
	 */
	@RequestMapping("/saveDict")
	@ResponseBody
	public Map<String, String> saveDict(HttpServletRequest request, DictEntity dictEntity) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			if (StringUtils.isNotEmpty(dictEntity.getDictType()) && StringUtils.isNotEmpty(dictEntity.getDictName())) {
				// 冲突验证
				DictEntity existsDict = dictService.getDict(dictEntity.getDictType(), dictEntity.getDictName());
				if (null == dictEntity.getId()) {
					// 添加
					if (null != existsDict) {// 已存在，冲突
						result.put("code", "-1");
						result.put("msg", "该字典已存在，请重新输入！");
					} else {
						dictEntity.setIsDelete(IS_DELETE.NORMAL.getId());
						// 有，就用，没有就设为1：系统字典，不可修改
						dictEntity.setType(null == dictEntity.getType() ? 1 : dictEntity.getType());
						dictEntity.setCreater(getUserName());
						dictEntity.setModifier(getUserName());
						int rows = dictService.save(dictEntity);
						if (rows > 0) {
							result.put("code", "1");
							result.put("msg", "字典保存成功！");
						} else {
							result.put("code", "0");
							result.put("msg", "字典保存失败，请重试！");
						}
					}
				} else {
					// 修改
					if (null != existsDict && !existsDict.getId().equals(dictEntity.getId())) {
						result.put("code", "-1");
						result.put("msg", "该字典已存在，请重新输入！");
					} else {
						dictEntity.setModifier(getUserName());
						dictService.update(dictEntity);
						result.put("code", "1");
						result.put("msg", "字典修改成功！");
					}
				}
			} else {
				result.put("code", "0");
				result.put("msg", "字典类型及名称均不可为空！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", "-2");
			result.put("msg", "字典保存异常，请重试！");
		}
		return result;
	}

	// TODO 字典修改

	/**
	 * 查询订单列表信息
	 * 
	 * @param order
	 * @param request
	 * @return
	 * @author chenling
	 * @date 2017年7月18日 上午11:30:16
	 */
	@RequestMapping("/listKeyPage")
	@ResponseBody
	public JSONGrid listOrderPage(HttpServletRequest request, String keyType) {
		// 返回结果集查询
		JSONGrid resultList = null;
		// 获取分页参数列表
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		// 封装参数
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			paramMap.put("keyType", keyType);
			PageBean pageBean = keyMapService.listKeyMapByPageBean(pageParam, paramMap);
			resultList = new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询列表失败", logger, e);
			resultList = new JSONGrid();
		}
		return resultList;
	}

	/**
	 * 查询获取所有数据字典信息
	 * 
	 * @param request
	 * @return
	 * @author zhaieryuan
	 * @date 2017年4月19日 下午3:03:12
	 */
	@RequestMapping("/listKeyMapEntites")
	@ResponseBody
	public BaseReturn listKeyMapEntites(HttpServletRequest request, @RequestParam(required = true) String keyType) {
		BaseReturn baseReturn = new BaseReturn();
		List<KeyMapEntity> keyMapEntities = keyMapService.listKeyMap(keyType);
		if (keyMapEntities.size() > 0) {
			baseReturn.setData(keyMapEntities);
			baseReturn.setSuccess(1);
			baseReturn.setMsg("查询下拉信息成功");
		} else {
			baseReturn.setSuccess(-1);
			baseReturn.setMsg("查询下拉信息失败");
		}
		return baseReturn;
	}

	/**
	 * 新增下拉属性信息
	 * 
	 * @param keyMapEntity
	 * @param request
	 * @param response
	 * @return
	 * @author zhaieryuan
	 * @date 2017年5月8日 下午2:47:33
	 */
	@RequestMapping("/saveKeyMap")
	@ResponseBody
	public Map<String, Object> saveKeyMap(KeyMapEntity keyMapEntity, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			if (null != keyMapEntity && StringUtils.isNotEmpty(keyMapEntity.getKeyType()) && StringUtils.isNotEmpty(keyMapEntity.getKeyValue())) {
				// 验证是否存在该值
				resultMap.put("keyType", keyMapEntity.getKeyType());
				resultMap.put("keyValue", keyMapEntity.getKeyValue());
				List<KeyMapEntity> listMap = keyMapService.listByTypeAndKeyVal(resultMap);
				if (null == keyMapEntity.getId()) {
					// 新增
					if (null != listMap && listMap.size() > 0) {
						resultMap.put("msg", "添加失败，已存在该基础数据记录！");
						resultMap.put("code", 0);
						return resultMap;
					} else {
						// 添加
						keyMapEntity.setIsDelete(1);
						keyMapService.saveKeyMapEntity(keyMapEntity);
						resultMap.put("msg", "基础数据保存成功！");
						resultMap.put("code", 1);
					}
				} else {
					// 修改
					if (null != listMap && listMap.size() > 0) {
						for (KeyMapEntity dbItem : listMap) {
							if (!dbItem.getId().equals(keyMapEntity.getId())) {
								resultMap.put("msg", "添加失败，已存在该基础数据记录！");
								resultMap.put("code", 0);
								return resultMap;
							}
						}
					}
					keyMapService.modifyKeymap(keyMapEntity);
					resultMap.put("msg", "基础数据修改成功！");
					resultMap.put("code", 1);
				}
				// List<KeyMapEntity> listMap =
				// keyMapService.listByTypeAndKeyVal(resultMap);
				// if (null != listMap && listMap.size() > 0) {
				// resultMap.put("msg", "添加失败，已存在该基础数据记录！");
				// resultMap.put("code", 0);
				// } else {
				// if(null == keyMapEntity.getId()) {
				// //添加
				// keyMapEntity.setIsDelete(1);
				// keyMapService.saveKeyMapEntity(keyMapEntity);
				// } else {
				// //修改
				// keyMapService.modifyBrandEntity(keyMapEntity);
				// }
				// resultMap.put("msg", "基础数据保存成功！");
				// resultMap.put("code", 1);
				// }
			} else {
				resultMap.put("msg", "添加失败，传入值为空！");
				resultMap.put("code", 0);
			}
		} catch (Exception e) {
			handleException("新增下拉信息异常", logger, e);
			e.printStackTrace();
			resultMap.put("msg", "添加异常！");
			resultMap.put("code", 0);
		}
		return resultMap;
	}

	/**
	 * 跳转下拉属性修改页
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @author zhaieryuan
	 * @date 2017年5月8日 下午2:51:28
	 */
	@RequestMapping("/toKeyMapModifyPage")
	public ModelAndView toKeyMapModifyPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("opFlag", "edit");
		String id = request.getParameter("id");
		try {
			KeyMapEntity keyMapEntity = keyMapService.getById(id);
			request.setAttribute("keyMapEntity", keyMapEntity);
			mv.setViewName("/settings/keymap_manage/keymap_form");
		} catch (Exception e) {
			handleException("跳转编辑错误页面", logger, e);
			mv.setViewName("/error/500");
		}
		return mv;
	}

	/**
	 * 修改
	 * 
	 * @param keyMapEntity
	 * @param request
	 * @param response
	 * @return
	 * @author zhaieryuan
	 * @date 2017年5月8日 下午2:53:48
	 */
	@RequestMapping("/updateKeyMap")
	@ResponseBody
	public Map<String, Object> updateKeyMap(KeyMapEntity keyMapEntity, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			keyMapEntity.setModifier(this.getUserName());
			keyMapEntity.setModifyTime(new Date());
			keyMapService.modifyKeymap(keyMapEntity);
			resultMap.put("msg", "修改成功");
			resultMap.put("success", 1);
			resultMap.put("data", keyMapEntity);
		} catch (Exception e) {
			handleException("修改下拉属性异常", logger, e);
			resultMap.put("msg", "修改失败");
			resultMap.put("success", 0);
		}
		return resultMap;
	}

	/**
	 * 根据id删除字典信息
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @author zhaieryuan
	 * @date 2017年5月8日 下午5:56:41
	 */
	@RequestMapping("/deleteKeyMap")
	@ResponseBody
	public Map<String, String> deleteKeyMap(@RequestParam(required = true) String id, @RequestParam(required = true) String keyType,
	        HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			KeyMapEntity keyMapEntity = new KeyMapEntity();
			keyMapEntity.setId(Long.parseLong(id));
			keyMapEntity.setModifier(this.getUserName());
			keyMapEntity.setModifyTime(new Date());
			keyMapEntity.setKeyType(keyType);
			keyMapEntity.setIsDelete(0);
			keyMapService.modifyKeymap(keyMapEntity);
			result.put("resultCode", "1");
			result.put("resultMsg", "删除成功");
		} catch (Exception e) {
			handleException("跳转编辑错误页面", logger, e);
			result.put("resultCode", "0");
			result.put("resultMsg", "删除失败");
		}
		return result;
	}

	/**
	 * 下拉测试Demo
	 * 
	 * @param request
	 * @return
	 * @author zhaieryuan
	 * @date 2017年5月8日 下午1:46:11
	 */
	@RequestMapping("/toSelectDemoPage")
	public ModelAndView toSelectDemoPage(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("demo/select_demo");
		return mv;
	}

	/**
	 * 根据keyType修改字典信息
	 * 
	 * @param request
	 * @return
	 * @author wangchuang
	 * @date 2017年7月24日 下午1:46:36
	 */
	@RequestMapping("/modifyKeyMapByKeyType")
	@ResponseBody
	public Map<String, String> modifyKeyMapByKeyType(HttpServletRequest request) {
		Map<String, String> result = new HashMap<String, String>();
		String keyType = request.getParameter("keyType");
		String keyValue = request.getParameter("keyValue");
		try {
			KeyMapEntity keyMapEntity = new KeyMapEntity();
			keyMapEntity.setKeyType(keyType);
			keyMapEntity.setKeyValue(keyValue);
			keyMapService.modifyKeyMapByKeyType(keyMapEntity);
			result.put("resultCode", "1");
			result.put("resultMsg", "修改成功");
		} catch (Exception e) {
			handleException("修改错误", logger, e);
			result.put("resultCode", "0");
			result.put("resultMsg", "修改失败");
		}
		return result;
	}

	/**
	 * 执行新增关键字信息
	 * 
	 * @param request
	 * @return
	 * @author shanchuangye
	 * @date 2017年7月24日 下午5:12:45
	 */
	@RequestMapping("/toAddKeyPage")
	public ModelAndView toAddKeyPage(HttpServletRequest request, String id, String keyType, String option) {
		ModelAndView mv = new ModelAndView("/sysconfig/key_form");
		if (id != null && id != "") {
			try {
				KeyMapEntity keyMapEntity = keyMapService.getById(id);
				mv.addObject("keyMapEntity", keyMapEntity);
			} catch (Exception e) {
				handleException("查询keyMap异常", logger, e);
				e.printStackTrace();
			}
		} else if ("".equals(keyType)) {
			keyType = "brand";
		}
		mv.addObject("id", id);
		mv.addObject("keyType", keyType);
		mv.addObject("option", option);
		return mv;
	}
}
